package com.yuebao.mq;

import com.yuebao.exception.CustomerException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@RocketMQMessageListener(topic = "transaction",consumerGroup = "${rocketmq.consumer.group}",messageModel = MessageModel.BROADCASTING )
@Component
@Slf4j
public class TransactionEventReceiver implements RocketMQListener<MessageExt> {
    
    @Resource
    private EventMqReceiver eventMqReceiver;
    
    @Override
    public void onMessage(MessageExt message) {
        byte[] body = new byte[0];
        try {
            body = Optional.ofNullable(message.getBody())
                    .orElseThrow(() -> new CustomerException(String.format("event消息为空, messageId:【%s】", message.getMsgId())));
        } catch (CustomerException e) {
            e.printStackTrace();
        }
        String eventString = new String(body);
        String messageId = message.getMsgId();
        log.info("message start consume==》messageId:【{}】, event: 【{}】", message.getMsgId(), eventString);
        eventMqReceiver.handleReceiveMessage(eventString, messageId, message.getQueueOffset());
    }
    //todo 更改订单支付状态


    //成功

    //失败
}

//        //1.解析消息内容
//        String body = new String(messageExt.getBody(),"UTF-8");
//        TradePay tradePay = JSON.parseObject(body,TradePay.class);
//        //2.根据订单ID查询订单对象
//        TradeOrder tradeOrder = orderMapper.selectByPrimaryKey(tradePay.getOrderId());
//        //3.更改订单支付状态为已支付
//        tradeOrder.setPayStatus(ShopCode.SHOP_ORDER_PAY_STATUS_IS_PAY.getCode());
//        //4.更新订单数据到数据库
//        orderMapper.updateByPrimaryKey(tradeOrder);
//        log.info("更改订单支付状态为已支付");
